<!--
 * @Descripttion: 
 * @version: 
 * @Author: cyj
 * @Date: 2022-12-27 23:12:53
-->
<template>
    <div class="comment-page">
        <!-- 输入框 -->
        <div class="textinput">
            <el-input ref="inputs" v-model.trim="text" :rows="3" type="textarea" placeholder="请输入内容" maxlength="140"
                show-word-limit />
            <el-button class="btn" round small @click="submitComment">评论</el-button>
        </div>
        <!-- 评论列表 -->
        <div class="comment-list">
            <!-- 热门评论 -->
            <div class="hotcomment" v-if="HotCommentList?.length !== 0">
                <h3>精彩评论</h3>
                <div class="item" v-for="(item, index) in HotCommentList" :key="index">
                    <CommentItem :item="item" :commentType="instance.props.commentType"
                        :commentresId="instance.props.commentresId" @getReplyComment="getReplyComment"></CommentItem>
                </div>
            </div>

            <!-- 最新评论 -->
            <div class="newcomment">
                <h3>最新评论({{ NewCommentTotal }})</h3>
                <div class="item" v-for="(item, index) in NewcommentList" :key="index">
                    <CommentItem :item="item" :commentType="instance.props.commentType"
                        :commentresId="instance.props.commentresId" @getReplyComment="getReplyComment"></CommentItem>
                </div>
            </div>
            <!-- 分页器 -->
            <div class="pagination">
                <el-pagination background small :total="NewCommentTotal" v-model:current-page="currentPage"
                    v-model:page-size="pageSize" @current-change="handleCurrentChange"
                    layout="total,prev, pager, next"></el-pagination>
            </div>
        </div>
    </div>
</template>

<script setup>
import { getNewComment, sendComment, replyComment } from '@/api/comment/comment.js'
import { ref, onMounted, getCurrentInstance } from 'vue'

import CommentItem from '@/components/content/comment/CommentItem.vue'

//引入pinia
import { useUserStore } from '@/store/user.js'
import { useMusicStore } from '@/store/music.js'
//创建仓库对象
const user = useUserStore()
const music = useMusicStore()
//收集输入的评论
let text = ref('')
//收集回复的评论
let replyText = ref('')

const instance = getCurrentInstance()
//最新评论数组
let NewcommentList = ref([])
//热门评论数组
let HotCommentList = ref([])
//最新评论总数
let NewCommentTotal = ref(0)
//分页器属性
let currentPage = ref(1)
let pageSize = ref(60)
//评论相关属性
let submitType = ref(1) //评论提交类型 1是发送 2是回复
let replyId = ref('')  //回复评论的id
let replyUname = ref('')  //回复的用户名称

const props = defineProps({
    //资源类型
    // 0:歌曲music 1:mv 2:歌单playlist 3:专辑album 5:视频video
    commentType: Number,
    //资源id
    commentresId: {
        type: [Number, String]
    }
})

//切换当前页
function handleCurrentChange(page) {
    currentPage.value = page
    getNewCommentBy(page)
    window.scroll(0, 0)
    if (music.isShowSongDetail) {  //正在展示歌曲详情页
        let com = document.querySelector('.playing-song-detail')
        let comment = document.querySelector('.bottom-content')
        com.scrollTo({  //把歌曲详细页滚动到评论的高度
            top: comment.offsetTop
        })
    }
}

//第一个情况：直接评论
async function sendCommentBy() {
    let res = await sendComment(props.commentType, props.commentresId, text.value)
    if (res.status === 200) {
        //发送成功  
        text.value = ''  //先清空文本框
        setTimeout(() => {
            getNewCommentBy()  //刷新评论，再次获取最新评论
        }, 1000)
        //显示提示信息
        instance.appContext.config.globalProperties.$message({
            showClose: true,
            message: '评论成功!',
            type: 'success'
        })
    } else {
        instance.appContext.config.globalProperties.$message({
            showClose: true,
            message: '评论失败!请稍后再试',
            type: 'warning'
        })
    }
}

//第二个情况：回复某用户的评论
async function replyCommentBy() {
    //发送网络请求
    let res = await replyComment(props.commentType, props.commentresId, replyText.value, replyId.value)
    if (res.status === 200) {
        //回复成功 清空数据
        text.value = ''  //清空文本框
        replyText.value = ''   //清空回复信息
        submitType.value = 1  //修改评论类型为默认的1
        replyId.value = ''  //清空回复的用户id
        replyUname.value = ''   //清空要回复的用户名
        //刷新评论 获取最新评论
        setTimeout(() => {
            getNewCommentBy()
        }, 1000)
        //显示提示信息
        instance.appContext.config.globalProperties.$message({
            showClose: true,
            message: '回复成功!',
            type: 'success'
        })
    } else {
        instance.appContext.config.globalProperties.$message({
            showClose: true,
            message: '回复失败!请稍后再试',
            type: 'warning'
        })
    }
}

//自定义事件 —— 处理回复用户评论
function getReplyComment(replyInfo) {
    //将子组件传递的信息保存
    replyId.value = replyInfo.commentId
    replyUname.value = replyInfo.uname
    //滚动到输入框|文本框
    window.scroll(0, 100)
    text.value = `回复${replyUname.value}:`

    //获取文本框焦点
    instance.ctx.$refs.inputs.focus()
    //将评论提交类型改为回复
    submitType.value = 2

}

//提交评论
function submitComment() {
    //判断是否登录
    if (!user.isLogin) {  //没有登录
        instance.appContext.config.globalProperties.$message({
            showClose: true,
            message: '登录后才能点赞',
            type: 'warning'
        })
        return;
    }
    //登录后
    // console.log('登录后');
    //判断输入的评论是否为空
    if (text.value.trim() === '') {
        instance.appContext.config.globalProperties.$message({
            showClose: true,
            message: '评论失败,内容不能为空',
            type: 'warning'
        })
        return;

    } else { //输入内容不为空
        //判断是直接评论还是回复评论
        if (submitType.value === 1) {  //直接评论
            //直接发送评论
            sendCommentBy()
        } else {  //回复评论
            //分割字符串，获取正确的回复信息  从第一个:开始分割
            let temp = text.value.slice(text.value.indexOf(":") + 1)
            if (temp.trim() === '') {
                instance.appContext.config.globalProperties.$message({
                    showClose: true,
                    message: '回复失败,回复内容不能为空',
                    type: 'warning'
                })
                return;
            }
            //保存正确的回复信息
            replyText.value = temp
            //回复某用户评论
            replyCommentBy()
        }
    }


}

//获取最新评论
async function getNewCommentBy(page = 1) {
    let type = ''
    //判断传入的资源类型是什么
    switch (props.commentType) {
        case 0:
            type = 'music'
            break;
        case 1:
            type = 'mv'
            break;
        case 2:
            type = 'playlist'
            break;
        case 3:
            type = "album";
            break;
        case 5:
            type = "video";
            break;
    }
    let offset = (page - 1) * 60
    let res = await getNewComment(type, props.commentresId, offset)
    if (res.status === 200) {
        //保存最新评论
        NewcommentList.value = res.data.comments
        //保存最新评论总数
        NewCommentTotal.value = res.data.total
        //如果热门评论存在数组，就保存
        if (page === 1 && res.data.hotComments?.length != 0) {
            HotCommentList.value = res.data.hotComments
        } else {
            //清空热门数组
            HotCommentList.value = []
        }
    }
}

onMounted(() => {
    //获取最新评论和热门评论
    getNewCommentBy()
})

</script>

<style lang="scss" scoped>
.comment-page {
    margin: 0 30px;
    position: relative;

    .textinput {
        text-align: right;

        .btn {
            margin-top: 10px;
        }
    }

    .comment-list {
        .hotcomment {}

        .newcomment {
            margin-top: 50px;
        }
    }
}

.el-button:focus,
.el-button:hover {
    color: black !important;
    background-color: #f2f2f2 !important;
    border-color: #e0e0e0 !important;
}

.pagination {
    margin-top: 20px;
    display: flex;
    justify-content: center;
}
</style>